<template>
	<web-view v-if="data.url" :src="data.url"></web-view>
	<view class="pubbox" v-else>
		<!-- #ifdef H5 -->
		<fui-sticky>
			<fui-nav-bar :title="title" @leftClick="leftClick">
				<fui-icon name="arrowleft"></fui-icon>
			</fui-nav-bar>
		</fui-sticky>
		<!-- #endif -->

		<view class="box">
			<LandScape></LandScape>
			<view class="title">
				<fui-section style="padding: 0;" color="#fd5531" title="请选择分类" isLine></fui-section>
				<view class="wztype" v-if="type=='项目'">
					<view class="typelist">
						<view class="typeitem" v-for="(item,index) in classificationxm" :key="item._id" :class="data.form.category_id==item._id?'typeactive':''" @click="changetype(item._id)">
							<view class="typename">
								{{item.name}}
							</view>
						</view>
					</view>
				</view>
				<view class="wztype" v-if="type=='软件'">
					<view class="typelist">
						<view class="typeitem" v-for="(item,index) in classificationrj" :key="item._id" :class="data.form.category_id==item._id?'typeactive':''" @click="changetype(item._id)">
							<view class="typename">
								{{item.name}}
							</view>
						</view>
					</view>
				</view>
				<fui-section style="margin-top: 40rpx;padding: 0;" v-if="type=='软件'" title="软件logo" color="#fd5531" isLine></fui-section>
				<uni-file-picker :auto-upload="false" v-if="type=='软件'" ref="files" style="margin-top: 20rpx;" @delete="deconsteLogo" @select="successLogo" file-mediatype="image" mode="grid" :limit="1" />
				<fui-section style="margin-top: 40rpx;padding: 0;" :title="type+'标题'" color="#fd5531" isLine></fui-section>
				<fui-textarea size="28" placeholderStyle="color:#bfbfbf;font-size:26rpx" radius='15' :maxlength="data.maxTitLen" v-model="data.form.title" style="margin-top: 20rpx;" backgroundColor="#f3f5f7" minHeight="200" placeholder="请输入标题 (必填)"></fui-textarea>
				<fui-section v-if="type=='软件'" style="margin-top: 20rpx;padding: 0;" color="#fd5531" title="请填写下载链接" isLine></fui-section>
				<fui-textarea size="28" placeholderStyle="color:#bfbfbf;font-size:26rpx" :maxlength="-1" v-if="type=='软件'" radius='15' v-model="data.form.application_url" style="margin-top: 20rpx;" backgroundColor="#f3f5f7" height="40rpx" min-height="40rpx" placeholder="请输入下载链接 (必填)"></fui-textarea>
				<fui-section style="margin-top: 20rpx;padding: 0;" v-if="type=='软件'" title="软件摘要" color="#fd5531" isLine></fui-section>
				<fui-textarea size="28" placeholderStyle="color:#bfbfbf;font-size:26rpx" :maxlength="5" radius='15' v-if="type=='软件'" maxlength="5" v-model="data.form.excerpt" style="margin-top: 20rpx;" backgroundColor="#f3f5f7" height="40rpx" min-height="40rpx" placeholder="请输入软件摘要 (选填-字数不得超过5个)"></fui-textarea>
				<fui-section style="margin-top: 20rpx;padding: 0;" color="#fd5531" title="内容描述" isLine></fui-section>
				<fui-textarea size="28" placeholderStyle="color:#bfbfbf;font-size:26rpx" :maxlength="-1" radius='15' v-model="data.form.content" style="margin-top: 20rpx;" backgroundColor="#f3f5f7" minHeight="400rpx" placeholder="请输入描述 (必填)"></fui-textarea>
				
				<fui-section style="margin-top: 20rpx;padding: 0;" color="#fd5531" title="上传图片" isLine></fui-section>
				<uni-file-picker :auto-upload="false" ref="files" style="margin-top: 20rpx;" @select="selectIMG" @delete="delIMG" file-mediatype="image" mode="grid" :limit="limit" />

				<view v-if="type=='项目'">
					<fui-section v-if="false" style="margin-top: 40rpx;padding: 0;" color="#fd5531" title="请选择是否上头条" isLine>
						<template v-slot:right>
							<fui-switch :disabled="model.disabled" :checked='data.form.is_headline' :scaleRatio="0.8" @change="changeSwitch"></fui-switch>
						</template>
					</fui-section>
				</view>

				<fui-button style="margin-top: 30rpx;background-color: var(--fui-color-primary);" :text="'确认发布 ('+data.price+'元)'" @click="publishDebounce"></fui-button>
				<pay ref="uniPay"></pay>
				<fui-loading v-if="data.loading" :isFixed="true" srcCol="/static/images/component/loading_white.png" text="正在加载..."></fui-loading>
			</view>
			<!-- 扫码支付 -->
		</view>
	</view>
</template>

<script setup>
	const payApi = uniCloud.importObject('qc-pay',{
		customUI: true
	})
	import { setDiscount, debounce } from "@/utils/index.js"
	import { ConfigStore } from '@/store/modules/config.js'
	const apiDetail = uniCloud.importObject('qc-asset', {
		customUI: true // 取消自动展示的交互提示界面
	})
	const api = uniCloud.importObject('qc-article', { customUI: true })
	import { useUploadFile } from '@/hooks/useUploadFile.js'
	const { uploadFile, deleteFile, getFileInfo } = useUploadFile()
	import { LoginStore } from "@/store/modules/login.js";
	import { onLoad } from "@dcloudio/uni-app";
	import { ref, reactive, computed, nextTick } from 'vue'
	const userInfo = computed(() => (LoginStore().userInfo))
	const classificationxm = computed(() => (ConfigStore().classification["0"]))
	const classificationrj = computed(() => (ConfigStore().classification["1"]))
	const type = ref(null)
	const title = ref('发布')
	const show = ref(true)
	const roofindex = ref(0)
	const limit = ref(9)
	const typelist = ref([])
	//置顶列表
	const rooflist = ref(null)

	const data = reactive({
		form: {},
		publishPrice: 0, //发布价格
		price: 0, //总价格
		sticky_price: 0, //置顶价格
		loading: false, //loading
		maxTitLen: "", //标题最长限制
		url: '' //扫码支付的url
	})
	const getType = (e) => {
		if (e == 0) {
			return '项目'
		} else if (e == 1) {
			return '软件'
		}
	}
	onLoad(async (e) => {
		let item = JSON.parse(e.title)
		type.value = getType(item.publish_type)
		title.value += getType(item.publish_type)
		if (type.value == '项目') {
			data.maxTitLen = 100
			data.form = {
				user_id: userInfo?.value?._id,
				publish_type: '0',
				category_id: '', //分类id
				title: '', // 标题
				articles_img: [],
				content: '', //文章内容
				is_sticky: false, //是否置顶
				sticky_time: '', //置顶天数
			}
			const res1 = await apiDetail.getPricing({ category_id: item._id })
			rooflist.value = res1.data?.sticky_cost
			data.publishPrice = res1.data?.articles
			if (userInfo?.value?.push_num < userInfo?.value?.vipPower?.publishNum) {
				data.publishPrice = 0
			}
			data.price += data.publishPrice
			limit.value = 9
			data.form.category_id = classificationxm?.value[0]?._id
		} else {
			data.maxTitLen = 100
			data.form = {
				user_id: userInfo?.value?._id,
				publish_type: '1',
				category_id: '', //分类id
				title: '', // 软件名称
				application_img: [], //应用截图
				application_logo: [], //应用logo
				application_url: '', //下载地址
				excerpt: '', //应用摘要
				content: '', //应用介绍
				is_sticky: false, //是否置顶
				sticky_time: '', //置顶天数
			}
			const res1 = await apiDetail.getPricing({ category_id: item._id })
			rooflist.value = res1.data?.sticky_cost
			data.publishPrice = res1.data?.application
			data.price += data.publishPrice
			limit.value = 9
			data.form.category_id = classificationrj?.value[0]?._id
		}
	})
	const model = reactive({
		showmodal: false,
		ranking: null,
		showTop: false,
		topList: [],
		disabled: false
	})


	function changetype(index) {
		data.form.category_id = index
	}

	function roof(item, index) {
		if (index !== 0) {
			data.form.is_sticky = true
			data.form.sticky_time = item.valid_time
		} else {
			data.form.is_sticky = false
		}
		roofindex.value = index
		data.sticky_price = rooflist.value[index].sticky_price
		if (type.value == '项目') {
			data.price = data.sticky_price + data.onehead_price * data.form.headline_time + data.publishPrice
		} else {
			data.price = data.sticky_price + data.publishPrice
		}
	}

	// #ifdef H5
	function leftClick() {
		uni.navigateBack()
	}
	// #endif
	//上传logo图片
	let fileIDLogo = []
	const successLogo = async (e) => {
		const res = await uploadFile(e.tempFiles, 'application', 'url')
		fileIDLogo = res
	}
	const deconsteLogo = (e) => {
		deleteFile(fileIDLogo, e)
		fileIDLogo.forEach((vm, i) => {
			if (vm.filePath == e.tempFilePath) {
				fileIDLogo.splice(i, 1)
			}
		})
	}

	const delAva = (e) => {
		deleteFile(fileren, e)
		fileren.forEach((vm, i) => {
			if (vm.filePath == e.tempFilePath) {
				fileren.splice(i, 1)
			}
		})
	}

	//上传图片
	let fileIDs = []
	const selectIMG = async (e) => {
		const res = await uploadFile(e.tempFiles, 'article', 'file')
		res.forEach(item => {
			fileIDs.push(item)
		})
	}

	const delIMG = (e) => {
		deleteFile(fileIDs, e)
		fileIDs.forEach((vm, i) => {
			if (vm.filePath == e.tempFilePath) {
				fileIDs.splice(i, 1)
			}
		})
	}
	const uniPay = ref(null)
	const createPayment = async (price) => {
		let subject = ""
		if (type.value == "项目") {
			subject = "发布文章"
		} else {
			subject = "发布应用"
		}

		if (price > 0) {
			uniPay?.value.open({
				data: {
					total_price: data.price, //原价
					total_fee: setDiscount(userInfo?.value?.vipPower?.discount, price),
					subject: subject,
					body: subject,
					type: "ad",
				},
				onCreate: res => {
					// 处理支付订单创建成功的逻辑
					console.log(res)
				},
				onSuccess: async (res) => {
					console.log(res);
					if (res.code == 0 && res.user_order_success) {
						if (res.orderPaid == false && res.url) {
							const resApi = await payApi.addOrdersLog({
								...data.form,
								out_trade_no: res.out_trade_no,
								key:subject
							})
							if(resApi.id){
								data.url = res.url
							}
						} else {
							const res1 = await api.createAd({
								...data.form,
								out_trade_no: res.out_trade_no,
								auth_audit: userInfo?.value?.vipPower?.auth_audit
							})
							uni.fui.toast(res1.errMsg)
							if (res1.errCode == 0) {
								setTimeout(() => {
									uni.navigateBack()
								}, 1000)
							}
							uni.$emit("resetUpScroll", true)
						}
					}
				},
				onFail: res => {
					// 处理支付失败的逻辑
				},
				onCancel: res => {
					// 处理用户取消支付的逻辑
				}
			})
		} else {
			try {
				data.loading = true
				const res1 = await api.createAd({ ...data.form, auth_audit: userInfo?.value?.vipPower?.auth_audit })
				data.loading = false
				uni.fui.toast(res1.errMsg)
				if (res1.errCode == 0) {
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)
				}
			} catch (e) {
				data.loading = false
				//TODO handle the exception
			}
		}

	}
	// 防抖
	const publishDebounce = debounce(publish, 500)
	//发布
	async function publish() {
		if (!data.form.category_id) return uni.fui.toast('请选择分类')
		if (!data.form.title) return uni.fui.toast('请填写标题')
		if (!data.form.content) return uni.fui.toast('请填写内容')
		if (data.form.is_sticky == false) {
			delete data.form.sticky_time
		}
		if (type.value == '项目') {
			if (fileIDs.length == 0) return uni.fui.toast('最少上传一张图片')
			data.form.articles_img = fileIDs.map(x => x.fileID)
			createPayment(data.price)
		} else if (type.value == '软件') {
			if (fileIDLogo.length == 0) return uni.fui.toast('请上传软件LOGO')
			if (!data.form.application_url) return uni.fui.toast('请输入应用下载地址')
			if (data.form.application_url.indexOf('http') == -1) return uni.fui.toast('请输入正确的下载链接')
			if (fileIDs.length == 0) return uni.fui.toast('最少上传一张图片')
			data.form.application_logo = fileIDLogo[0].fileID
			data.form.application_img = fileIDs.map(x => x.fileID)
			if (data.price > 0) {
				createPayment(data.price)
			} else {
				createPayment(data.price)
			}
		}
	}
</script>

<style lang="scss" scoped>
	:deep() {
		.file-picker__box-content {
			background-color: #f8f9f9;
		}
	}

	.fui-switch__input {
		margin-left: 40rpx;
	}

	.top_box {
		padding: 32rpx 32rpx 12rpx 32rpx;
	}

	.typelist {
		margin-top: 30rpx;
		display: flex;
		justify-content: left;
		flex-wrap: wrap;
	}

	.typeitem {
		border: 1px solid #333333;
		padding: 0rpx 38rpx;
		border-radius: 30rpx;
		margin-right: 20rpx;
		margin-top: 10rpx;
		height: 60rpx;
		line-height: 60rpx;
	}

	.typeactive {
		background: linear-gradient(to right top, #ff6f49, #ff5a5e);
		border: 1px solid var(--fui-color-primary);
		color: #fff;
	}

	.typename {
		font-size: 26rpx;
	}

	.rooflist {
		display: flex;
		justify-content: space-around;
		flex-wrap: wrap;
	}

	.roofitem {
		display: flex;
		width: 20%;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;
		background-color: #f3f5f7;
		margin-top: 20rpx;
		padding: 52rpx 32rpx;
		border-radius: 16rpx;
	}

	.roofactive {
		border: 1px solid var(--fui-color-primary);
	}

	.roofname {
		color: var(--fui-color-subtitle);
		font-size: 26rpx;
	}

	.roofprice {
		color: var(--fui-color-primary);
		font-weight: bold;
		font-size: 40rpx;
	}

	.file-picker__box {
		background-color: #f3f5f7 !important;
	}

	.box {
		padding: 22rpx;
	}

	.container {
		width: 100%;
		background-color: var(--fui-bg-color);
	}

	.title {
		// text-align: center;
		font-size: 35rpx;
		font-weight: bold;
	}

	.pubbox {
		background-color: var(--fui-bg-color);
	}
</style>